'use client';

import { Button, Form, Input, Select, Switch, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';

const { Option } = Select;

const formFieldTypes = [
  { label: '输入框', value: 'text' },
  { label: '文本域', value: 'textarea' },
  { label: '单选框', value: 'radio' },
  { label: '复选框', value: 'checkbox' },
  { label: '下拉框', value: 'select' },
];

const FormBuilder = ({ value, onChange }: { value?: any, onChange?: (value: any) => void }) => {
  // 兼容传入的 value 既可能是 { fields: [] } 对象，也可能直接是字段数组
  const initialFields = Array.isArray(value) ? value : (value?.fields ?? []);

  const onFormChange = (_changedValues: any, allValues: any) => {
    // 统一回传为 { fields: [...] }，保持与后端存储结构一致
    onChange?.({ fields: allValues.fields || [] });
  };

  return (
    <Form
      name="dynamic_form_builder"
      onValuesChange={onFormChange}
      initialValues={{ fields: initialFields }}
      autoComplete="off"
    >
      <Form.List name="fields">
        {(fields, { add, remove }) => (
          <>
            {fields.map(({ key, name, ...restField }) => (
              <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                <Form.Item
                  {...restField}
                  name={[name, 'type']}
                  rules={[{ required: true, message: '请选择字段类型' }]}
                >
                  <Select options={formFieldTypes} placeholder="字段类型" style={{ width: 120 }} />
                </Form.Item>
                <Form.Item
                  {...restField}
                  name={[name, 'label']}
                  rules={[{ required: true, message: '请输入字段标签' }]}
                >
                  <Input placeholder="字段标签" />
                </Form.Item>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, curValues) =>
                    prevValues.fields[name]?.type !== curValues.fields[name]?.type
                  }
                >
                  {({ getFieldValue }) =>
                    ['text', 'textarea', 'select'].includes(getFieldValue(['fields', name, 'type'])) ? (
                      <Form.Item
                        {...restField}
                        name={[name, 'placeholder']}
                      >
                        <Input placeholder="占位提示" />
                      </Form.Item>
                    ) : null
                  }
                </Form.Item>
                <Form.Item
                  {...restField}
                  name={[name, 'required']}
                  valuePropName="checked"
                >
                  <Switch checkedChildren="必填" unCheckedChildren="非必填" />
                </Form.Item>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, curValues) =>
                    prevValues.fields[name]?.type !== curValues.fields[name]?.type
                  }
                >
                  {({ getFieldValue }) =>
                    getFieldValue(['fields', name, 'type']) === 'select' ? (
                      <Form.Item
                        {...restField}
                        name={[name, 'multiple']}
                        valuePropName="checked"
                      >
                        <Switch checkedChildren="多选" unCheckedChildren="单选" />
                      </Form.Item>
                    ) : null
                  }
                </Form.Item>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, curValues) =>
                    prevValues.fields[name]?.type !== curValues.fields[name]?.type
                  }
                >
                  {({ getFieldValue }) =>
                    ['radio', 'checkbox', 'select'].includes(getFieldValue(['fields', name, 'type'])) ? (
                      <Form.List name={[name, 'options']}>
                        {(options, { add: addOption, remove: removeOption }) => (
                          <>
                            {options.map((option, optionIndex) => (
                              <Space key={option.key}>
                                <Form.Item
                                  name={[optionIndex, 'label']}
                                  rules={[{ required: true, message: '请输入选项标签' }]}
                                >
                                  <Input placeholder="选项标签" />
                                </Form.Item>
                                <Form.Item
                                  name={[optionIndex, 'value']}
                                  rules={[{ required: true, message: '请输入选项值' }]}
                                >
                                  <Input placeholder="选项值" />
                                </Form.Item>
                                <MinusCircleOutlined onClick={() => removeOption(option.name)} />
                              </Space>
                            ))}
                            <Form.Item>
                              <Button type="dashed" onClick={() => addOption()} block icon={<PlusOutlined />}>
                                添加选项
                              </Button>
                            </Form.Item>
                          </>
                        )}
                      </Form.List>
                    ) : null
                  }
                </Form.Item>
                <MinusCircleOutlined onClick={() => remove(name)} />
              </Space>
            ))}
            <Form.Item>
              <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                添加字段
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
    </Form>
  );
};

export default FormBuilder;